public with sharing class BudgetProductCatesController {
	public  Map<String , BudgetProductCatesBean> bpcMap;
	public String msg {get;set;}
	public String resJson {get;private set;}//结果
	public String saveJson {get;set;}
	public Boolean isSuccess {get;private set;}

    public BudgetProductCatesController() {
       setNil();
        getBudgetData();
    }

    public void  getBudgetData(){
    	 bpcMap  = new Map<String , BudgetProductCatesBean>();
    	for (BudgetProductCates__c bp :[select Id ,Name , ProductLineFinance__c,ProductLineSale__c
    		,ProjectFinance__c,ProjectSale__c,BudgetCode__c ,Ordernum__c from BudgetProductCates__c 
    		] ) {
    		bpcMap.put(bp.BudgetCode__c,new BudgetProductCatesBean(bp));
    	}
    } 



    public void setNil(){
    	msg = '';
    	resJson = '';
    	saveJson = '';
    }
    public void save(){

    	msg = '';
    	List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
    	if(resList.size() == 0){
    		msg = '保存失败,没有数据!';
    		return;
    	}
    	List<BudgetProductCates__c>   tList = new List<BudgetProductCates__c>();
    	for (Object res : resList) {
	    	Map<String ,Object> o = (Map<String ,Object> )res;
	    	BudgetProductCates__c bp = new BudgetProductCates__c();
	    	bp.Name = String.valueOf(o.get('name'));
	    	bp.BudgetCode__c = String.valueOf(o.get('code'));
	    	bp.ProductLineFinance__c = String.valueOf(o.get('plinefinance'));
	    	bp.ProductLineSale__c = String.valueOf(o.get('plinesale'));
	    	bp.ProjectFinance__c = String.valueOf(o.get('pfinance'));
	    	bp.ProjectSale__c = String.valueOf(o.get('psale'));
	    	bp.Ordernum__c = getDecimalValue(o.get('order'));
	    	tList.add(bp);

	    }


    	SavePoint sp = Database.setSavepoint();
    	try {
    	    List<BudgetProductCates__c> deleList = [select Id from BudgetProductCates__c ];
    	    if(deleList != null && deleList.size() > 0)delete deleList;
    	    if(tList.size() > 0) insert tList;
    	    msg = '保存成功!';
    	    isSuccess = true;
    	}
    	catch (Exception e) {
    	   Database.rollback(sp);
    	    msg = '保存失败!'+e.getMessage();

    	}
    }
     private Decimal getDecimalValue(Object val){
        if(val == null)return null;

        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }
    //从nc 获取数据
    public void getNCData(){

    	msg = '';
    	String url = Label.queryResposityURL;
    
     	 //请求
		String sql = '{"data":" '+getSql()+'"}';
      	HttpRequest req = new HttpRequest();
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
      	HttpResponse res = Utils.postRequest(req, 2);
      	System.debug(res.getBody());
        if (res.getStatusCode() == 200) {
        	//System.debug(res.getBody());
            Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"result_msg":"查询成功！","result":1,"data":[{"invclinename":"自产开放生化","invclitem":"迈克产品","invclysname":"自产生化试剂(开放)","invclyscode":"M0610"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){

	            	List<BudgetProductCatesBean> resList = new List<BudgetProductCatesBean>();
	                List<Object> datas = (List<Object>)rs.get('data');
	                for(Object ob :datas){
	                	Map<String,object> o = (Map<String,object> )ob;
	                	BudgetProductCatesBean bpcb = new BudgetProductCatesBean(o);
	                	if(bpcMap.containsKey(bpcb.code)){
	                		bpcb.plinesale = bpcMap.get(bpcb.code).plinesale;
	                		bpcb.psale = bpcMap.get(bpcb.code).psale;
	                		bpcb.order =  bpcMap.get(bpcb.code).order;
	                	}
	                	resList.add(bpcb);
	                }
	                System.debug(resList);
      				resJson = EncodingUtil.urlEncode(JSON.serialize(resList), 'UTF-8') ;

	           	}else{
	           		msg = String.valueOf(rs.get('result_msg'));
	           	}

      		//resJson = EncodingUtil.urlEncode(res.getBody(), 'UTF-8') ;
		    }else{
		    	msg = '查询预算大类数据失败 : '+String.valueOf(r.get('msg'));
		    	 ///System.debug(res.toString());
		    	//resJson = EncodingUtil.urlEncode('{"result":"","code":"1","msg":"接口错误,查询失败!"}','UTF-8');
		    }

	    }else{
	    	msg = '查询预算大类数据失败 : '+res.getBody();
	    }


    }

    public String getSql(){

    	String sql = ' select  distinct m.doccode invclyscode,m.docname invclysname,';
    	 sql +=' case when substr(m.memo,1,instr(m.memo,\'@\',-1)-1)  is not null then substr(m.memo,1,instr(m.memo,\'@\',-1)-1) ';
    	 sql +='         when substr(m.memo,1,instr(m.memo,\'@\',-1)-1)  is  null and c.invcode like \'1%\' then \'迈克产品\' else \'非迈克产品\' end invclitem, ';
    	 sql +='        case when substr(m.memo,instr(m.memo,\'@\',-1)+1)  is not null and substr(m.memo,instr(m.memo,\'@\',-1)+1) not in (\'迈克产品\',\'非迈克产品\') ';
    	 sql +='        and  instr(m.memo,\'#\')>0  then substr(m.memo,instr(m.memo,\'@\',-1)+1,length(m.memo)-(instr(m.memo,\'@\',-1))-3)  ';
         sql +='       when substr(m.memo,instr(m.memo,\'@\',-1)+1)  is not null and substr(m.memo,instr(m.memo,\'@\',-1)+1) not in (\'迈克产品\',\'非迈克产品\')  ';
         sql +='       and   (instr(m.memo,\'#\')=0  or instr(m.memo,\'#\') is null)  then substr(m.memo,instr(m.memo,\'@\',-1)+1) ';
         sql +='        when substr(m.memo,instr(m.memo,\'@\',-1)+1)  in (\'迈克产品\',\'非迈克产品\') and c.invcode like \'1%\' then   \'自产其他试剂\' ';
         sql +='        when substr(m.memo,instr(m.memo,\'@\',-1)+1)  is  null and c.invcode like \'1%\' then \'自产其他试剂\' else \'代理试剂\'  end invclinename  ';
         sql +='       FROM bd_invbasdoc c LEFT JOIN bd_defdoc m ON c.def8=m.pk_defdoc where m.doccode is not null ORDER BY invclyscode ';
    	return sql;
    }

    public class  BudgetProductCatesBean{

    	public String  name ; //预算产品大类名称
    	public String  code ;//预算产品大类编码
    	public String  plinesale;//产品线销售
    	public String  plinefinance ;//产品线财务
    	public String  psale ;//项目 销售
    	public String  pfinance ;//项目 财务
    	public Decimal order ;
    	public BudgetProductCatesBean(Map<String,Object> obj){
    		name = String.valueOf(obj.get('invclysname'));
    		code = String.valueOf(obj.get('invclyscode'));
    		plinefinance = String.valueOf(obj.get('invclinename'));
    		pfinance = String.valueOf(obj.get('invclitem'));
    	}
    	public BudgetProductCatesBean(BudgetProductCates__c bp  ){
    		name  = bp.Name ;
    		code = bp.BudgetCode__c;
    		plinefinance = bp.ProductLineFinance__c;
    		pfinance = bp.ProjectFinance__c;
    		plinesale = bp.ProductLineSale__c;
    		psale = bp.ProjectSale__c;
    		order = bp.Ordernum__c;
    	}



    }
}